package com.jingli.pile.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jingli.pile.configuration.PushProperties;
import com.jingli.pile.constant.NotifyConstant;
import com.jingli.pile.domain.*;
import com.jingli.pile.entity.*;
import com.jingli.pile.service.PlatformInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class ThirdParty {
    private Logger logger = LoggerFactory.getLogger(ThirdParty.class);
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PushProperties pushProperties;
    @Autowired
    private PlatformInfoService platformInfoService;

    //获取token
    public String getToken(String platformId){
        String env = pushProperties.getEnv();
        QueryWrapper<PlatformInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("platform_id",platformId);
        infoQueryWrapper.eq("env",env);
        PlatformInfo platformInfo = platformInfoService.getOne(infoQueryWrapper);
        String token = (String) redisUtil.get(platformInfo.getPlatformSecretOrigin()+ NotifyConstant.TOKEN_PREDIX);
        logger.info("Redis中的token:{}",token);
        if (StringUtils.isEmpty(token)){
            JSONObject bodyJson = new JSONObject();
            JSONObject paramJson = new JSONObject();
            paramJson.put("PlatformID",platformInfo.getJingliPlatformId());
            paramJson.put("PlatformSecret",platformInfo.getJingliPlatformSecret());
            logger.info("待签名的参数:{}",JSONObject.toJSONString(paramJson));
            long timStamp = new Date().getTime();
            bodyJson.put("PlatformID",platformInfo.getJingliPlatformId());
            bodyJson.put("TimeStamp",String.valueOf(timStamp));
            String seq = SeqUtils.getUniqueInstance().getSeq();
            bodyJson.put("Seq",seq);
            String signParams = PileSignUtils.signParams(JSONObject.toJSONString(paramJson), platformInfo.getDataSecret(), platformInfo.getDataSecretIv());
            String sign;
            try {
                sign = HmacMd5Signature.hmacMd5(platformInfo.getJingliPlatformId()+signParams+timStamp+seq, platformInfo.getSignSecret());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            bodyJson.put("Data",signParams);
            bodyJson.put("Sig",sign);
            logger.info("请求URL:{}",platformInfo.getApiUrl()+NotifyConstant.QUERY_TOKEN);
            logger.info("请求参数:{}",JSONObject.toJSONString(bodyJson));
            String resultToken = HttpUtil.createPost(platformInfo.getApiUrl()+NotifyConstant.QUERY_TOKEN).body(JSONObject.toJSONString(bodyJson)).header("Content-Type","application/json;charset=UTF-8").execute().body();
            logger.info("请求来的token:{}",resultToken);
            if (StringUtils.isEmpty(resultToken)){
                return "";
            }
            JSONObject resObject = JSON.parseObject(resultToken);
            String data = resObject.getString("Data");
            String decrypted;
            try {
                decrypted = MessageEncryption.decrypt(data,platformInfo.getDataSecret(), platformInfo.getDataSecretIv());
                logger.info("token解密结果:{}",decrypted);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            TokenResult tokenResult = JSONObject.parseObject(decrypted, TokenResult.class);
            String accessToken = tokenResult.getAccessToken();
            redisUtil.set(platformInfo.getPlatformSecretOrigin()+ NotifyConstant.TOKEN_PREDIX,accessToken, tokenResult.getTokenAvailableTime()-2000);
            return accessToken;
        }
        return token;
    }
    //查询运营商信息
    public OperatorInfos queryOperatorInfo(String platformId,String pushUrl,Integer pageNo,Integer pageSize){
        JSONObject params = new JSONObject();
        params.put("PageNo",pageNo);
        params.put("PageSize",pageSize);
        String body = HttpUtil.createPost( pushUrl+ NotifyConstant.QUERY_OPERATOR_INFO).bearerAuth(getToken(platformId)).body(JSONObject.toJSONString(params)).execute().body();
        CommonResult<OperatorInfos> operatorInfos = JSONObject.parseObject(body, CommonResult.class);
        return (OperatorInfos) operatorInfos.getData();
    }

    //查询运营商信息
    public SupStationInfo queryStationInfos(String platformId,String pushUrl,String operatorID, String lastQueryTime, Integer pageNo, Integer pageSize, List<String> ids){
        JSONObject params = new JSONObject();
        params.put("PageNo",pageNo);
        params.put("PageSize",pageSize);
        params.put("OperatorID",operatorID);
        params.put("LastQueryTime",lastQueryTime);
        params.put("StationIDs",ids);
        String body = HttpUtil.createPost(pushUrl + NotifyConstant.QUERY_STATION_INFO).bearerAuth(getToken(platformId)).body(JSONObject.toJSONString(params)).execute().body();
        CommonResult<SupStationInfo> stationInfos = JSONObject.parseObject(body, CommonResult.class);
        return stationInfos.getData();
    }
    //查询充换电站状态信息
    public SupStationStatusInfo queryStationStatusInfo(String platformId,String pushUrl,String operatorID,List<String> ids){
        JSONObject params = new JSONObject();
        params.put("OperatorID",operatorID);
        params.put("StationIDs",ids);
        String body = HttpUtil.createPost(pushUrl + NotifyConstant.QUERY_STATION_STATS).bearerAuth(getToken(platformId)).body(JSONObject.toJSONString(params)).execute().body();
        CommonResult<SupStationStatusInfo> stationInfos = JSONObject.parseObject(body, CommonResult.class);
        return stationInfos.getData();
    }
    //推送充电设备接口状态信息
    public String notifyConnectorChangeStatus(String platformId,String pushUrl,String  data){
        String body = HttpUtil.createPost(pushUrl + NotifyConstant.NOTIFY_STATION_STATUS).bearerAuth(getToken(platformId)).body(data).execute().body();
        CommonResult<SupStationStatusInfo> stationInfos = JSONObject.parseObject(body, CommonResult.class);
        return JSONObject.toJSONString(stationInfos);
    }
    //推送充电状态信息
    public String notifyConnectorStatus(String platformId,String pushUrl,String data){
        return HttpUtil.createPost(pushUrl + NotifyConstant.NOTIFY_EQUIP_CHARGE_STATUS).bearerAuth(getToken(platformId)).body(data).execute().body();
    }
    //推送充换电站用能统计信息
    public String notifyOperationStats(String platformId,String pushUrl,String data){
        return HttpUtil.createPost(pushUrl + NotifyConstant.NOTIFY_OPERATION_STATS_INFO).bearerAuth(getToken(platformId)).body(data).execute().body();
    }
    //推送充电站充电订单信息
    public String notifyChargeOrderInfo(String platformId,String pushUrl,String chargingOrderData){
        logger.info("准备推送订单信息:{}",chargingOrderData);
        return HttpUtil.createPost(pushUrl + NotifyConstant.NOTIFY_CHARGE_ORDER_INFO).bearerAuth(getToken(platformId)).body(chargingOrderData).execute().body();
    }
}
